#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include "Log.hpp"
#include "InetAddr.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

const static int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(const int16_t port) : _port(port), _isrunning(true)
    {
    }

    void InitServer()
    {
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error, %s , %d \n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);

        // 2.0填充struct sockaddr_in 结构
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);

        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        //  local.sin_addr.s_addr = INADDR_ANY;

        local.sin_addr.s_addr = 0;

        // 2.1 bind sockfd 和网络信息（IP + port）
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error, %s , %d \n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socket bind success\n");
    }

    void Start()
    {
        _isrunning = true;

        while (_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                InetAddr client(peer);
                //std::cout << "client say# " << buffer << std::endl;
                LOG(DEBUG, "get message from : [%s : %d] %s\n",client.Ip().c_str(),client.Port(),buffer);
                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);
            }

        }

        _isrunning = false;
    }
    ~UdpServer() {}

private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip;

    bool _isrunning;
};